package com.feidee.bigdata.bloomfilterserv.init;

import com.feidee.bigdata.bloomfilterserv.constant.Constant;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;

@Component
public class ServiceInfoInit implements ApplicationListener<WebServerInitializedEvent> {

		@Override
		public void onApplicationEvent(WebServerInitializedEvent event) {

			//改方法会在继承于ApplicationRunner的ApplicationConfigInit方法之前执行
			int port = event.getWebServer().getPort();
			Constant.FALCON_START_NAME = Constant.FALCON_START_NAME + "_" + port;

			try {
				Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
				Collection<InetAddress> addresses = new ArrayList<InetAddress>();

				while (networkInterfaces.hasMoreElements()) {
					NetworkInterface networkInterface = networkInterfaces.nextElement();
					Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
					while (inetAddresses.hasMoreElements()) {
						InetAddress inetAddress = inetAddresses.nextElement();
						addresses.add(inetAddress);
					}
				}
				String ip = "";
				for (InetAddress address : addresses) {
					if (!address.isLoopbackAddress() && !address.getHostAddress().contains(":"))
						ip = address.getHostAddress();
				}
				String ip_last = ip.split("\\.")[3];
				Constant.UUID_IP_PREFIX = ip_last;
				for (int i = 0; i < 3 - ip_last.length(); i++) {
					Constant.UUID_IP_PREFIX = "0" + Constant.UUID_IP_PREFIX;
				}
			} catch (SocketException e) {
				throw new RuntimeException(e.getMessage(), e);
			}

			Constant.UUID_IP_PREFIX = Constant.UUID_IP_PREFIX + "_" + port + "_";

		}
}
